<template>
  <div>
    <el-button @click="addTable">add</el-button>
    <div id="toolbar-container"></div>
    <div id="editor-container" ref="tableEditor"></div>
  </div>
</template>
<script setup>
import { ref, onMounted, nextTick } from 'vue'
import '@wangeditor/editor/dist/css/style.css'
import { createEditor, createToolbar, DomEditor, SlateTransforms } from '@wangeditor/editor'

function genTableNode(rowNum, colNum) {
  // 拼接 rows
  const rows = []
  for (let i = 0; i < rowNum; i++) {
    // 拼接 cells
    const cells = []
    for (let j = 0; j < colNum; j++) {
      const cellNode = {
        type: 'table-cell',
        children: [{ text: '' }]
      }
      if (i === 0) {
        cellNode.isHeader = true // 第一行默认是 th
      }
      cells.push(cellNode)
    }

    // 生成 row
    rows.push({
      type: 'table-row',
      children: cells
    })
  }

  return {
    type: 'table',
    width: 'auto',
    children: rows
  }
}

let editor
let toolbar
const tableEditor = ref()
onMounted(() => {
  editor = createEditor({
    selector: tableEditor.value,
    mode: 'simple'
  })
  toolbar = createToolbar({
    editor,
    selector: '#toolbar-container'
    // config: {
    //   toolbarKeys: ['insertTable']
    // }
  })

  editor.on('insertTable', () => {
    console.log('==============')
  })

  const tb = DomEditor.getToolbar(editor)
  const curToolbarConfig = tb.getConfig()
  console.log(curToolbarConfig.toolbarKeys) // 当前菜单排序和分组

  nextTick(() => {
    const boldButton = document.querySelector('[data-title="加粗"]')
    if (boldButton) {
      boldButton.addEventListener('click', () => {
        console.log('加粗按钮被点击了')
      })
    }
  })
  window.editor = editor
  window.toolbar = toolbar
})

const addTable = () => {
  const nodes = genTableNode(3, 3)
  SlateTransforms.insertNodes(editor, nodes, { mode: 'highest' })
}
</script>
<style lang="less" scoped>
#editor-container {
  min-height: 300px;
  border: 1px solid red;
}
</style>
